package cn.com.wangluotongxin.database.service.impl;

import cn.com.wangluotongxin.admin.model.AdminMerchantsDatabase;
import cn.com.wangluotongxin.admin.model.AdminMerchantsDatabaseSync;
import cn.com.wangluotongxin.admin.model.constants.DatabaseReleaseStatus;
import cn.com.wangluotongxin.admin.model.constants.DatabaseRunStatus;
import cn.com.wangluotongxin.database.mapper.AdminMerchantsDatabaseSyncMapper;
import cn.com.wangluotongxin.database.service.IAdminMerchantsDatabaseService;
import cn.com.wangluotongxin.database.service.IAdminMerchantsDatabaseSyncService;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 网络通信-管理端-资源库操作记录 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-04-28
 */
@Service
public class AdminMerchantsDatabaseSyncServiceImpl extends ServiceImpl<AdminMerchantsDatabaseSyncMapper, AdminMerchantsDatabaseSync> implements IAdminMerchantsDatabaseSyncService {

    @Autowired
    private IAdminMerchantsDatabaseService merchantsDatabaseService;

    @Override
    public AdminMerchantsDatabaseSync createRecord(Integer databaseId, String title, String remark, Integer createUser, String createName, String channelId) {
        AdminMerchantsDatabaseSync adminMerchantsDatabaseSync = new AdminMerchantsDatabaseSync();
        adminMerchantsDatabaseSync.setDatabaseId(databaseId);
        adminMerchantsDatabaseSync.setTitle(title);
        adminMerchantsDatabaseSync.setRemark(remark);
        adminMerchantsDatabaseSync.setCreateUser(createUser);
        adminMerchantsDatabaseSync.setCreateName(createName);
        adminMerchantsDatabaseSync.setCreateTime(DateUtil.date());
        adminMerchantsDatabaseSync.setRunStatus(DatabaseRunStatus.RUNNING.getCode());
        this.save(adminMerchantsDatabaseSync);
        return adminMerchantsDatabaseSync;
    }

    @Override
    public void updateStatus(Integer id, DatabaseRunStatus status, String remark, String errorLog, String channelId) {
        this.update(new LambdaUpdateWrapper<AdminMerchantsDatabaseSync>()
                .set(AdminMerchantsDatabaseSync::getRunStatus,status.getCode())
                .set(AdminMerchantsDatabaseSync::getRemark, remark)
                .set(AdminMerchantsDatabaseSync::getErrorLog, errorLog)
                .eq(AdminMerchantsDatabaseSync::getId, id));

        AdminMerchantsDatabaseSync merchantsDatabaseSync = this.getById(id);
        if(status.getCode().equals(DatabaseRunStatus.FAIL.getCode())){
            AdminMerchantsDatabaseSync databaseSync = this.getById(id);
            merchantsDatabaseService.updateStatus(databaseSync.getDatabaseId(), DatabaseReleaseStatus.FAIL, errorLog, merchantsDatabaseSync.getCreateUser());
        }
    }
}
